<template>
  <div class="wrap">
    <div class="box">
      <p class="transport_data">
        打印日期:{{ $moment(new Date()).format("YYYY-MM-DD") }}
      </p>
      <el-form :model="form">
        <el-row :gutter="10"
                class="printHeader">
          <el-col :span="8"
                  class="left">
            <img class="printPic"
                 src="@/static/images/d_logo.png"
                 alt="logo" />
            <div class="span10 detail-row mb10"
                 style="word-break: break-all">
              <label>合同号:</label>
              <span class="detail-text">{{ waybillDetails.contractNo }}</span>
            </div>
            <div class="flex">
              <label>发货地址:</label>
              <div class="detail-text w80p">
                {{ fromAddress.province }}
                {{ fromAddress.city }}
                {{ fromAddress.district }}
                <br />
                <span class="wrap_value">{{ fromAddress.address }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="8"
                  class="center">
            <div class="span10">
              <span class="detail-text"
                    style="font-weight: bold">{{customer.customerName}}</span>
            </div>
          </el-col>
          <el-col :span="8"
                  class="right">
            <img class="printPic"
                 src="@/static/images/QRCode.png"
                 alt="code" />
            <div class="span10 detail-row mb10">
              <label>单据编号:</label>
              <span class="detail-text">
                {{ waybillDetails.orderNo }}
              </span>
            </div>
            <div class="flex">
              <label>收货地址:</label>
              <div class="detail-text w80p">
                {{ toAddress.province }}
                {{ toAddress.city }}
                {{ toAddress.district }}
                <br />
                <span class="wrap_value">{{ toAddress.address }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
        <hr />
        <simple-list :print="true"
                     :info="Object.assign(customer, { fromTime: waybillDetails.fromTime })"
                     :config-data="shipperPrintArr" />
        <hr />
        <simple-list :print="true"
                     :info="Object.assign(consignee, { toTime: waybillDetails.toTime })"
                     :config-data="consignPrintArr" />
        <hr />
        <simple-list v-if="$route.query.carrier"
                     :print="true"
                     :info="carrier"
                     :config-data="carrierPrintArr" />
        <hr v-if="$route.query.carrier" />
        <simple-list :print="true"
                     :info="
            Object.assign(
              waybillDetails.transportRequirement || {},
              { orderDesc: waybillDetails.desc },
              orderWaybillCache
            )
          "
                     :config-data="transportPrintArr" />
      </el-form>
      <el-table border
                :data="waybillDetails.goodsList">
        <template v-for="(column, index) in tableColumn">
          <el-table-column v-if="index === 0"
                           :key="index"
                           type="index"
                           align="center"
                           label="序号"
                           :width="column.width">
          </el-table-column>
          <el-table-column v-else
                           :key="index"
                           :prop="column.prop"
                           :label="column.label"
                           :width="column.width" />
        </template>
      </el-table>
      <goods-total v-if="totalList.length > 0"
                   :total-list="totalList"
                   :print="true"
                   class="mb20"
                   first-filed-name="goodsName"
                   :columns="tableColumn" />
      <div class="precautions">
        <label>注意事项：</label>
        <span class="detail-text">一、发货方托运的货物如实填写，不得隐瞒货物名称、数量及性质，不得在托运货物内夹带危险品、禁运物品。否则承运方在运输途中为此造成
          损失均由甲方负责。 <br />
          二、发货方若不跟人押车，卸货地址务必填清，货物包装必须完整无损，承运方按卸货地址给予按期，完整无缺运到和办理交接手续，否则造成
          损失各负其责。 <br />
          三、发货方托运货物时、必须参加保险，如不参加保险，出现货损、货差由发货方自负。
        </span>
      </div>
      <el-row :gutter="10"
              class="sign">
        <el-col :span="8">
          <label>核对人: </label>
          <span class="sign-text"></span>
        </el-col>
        <el-col :span="8">
          <label>签收人: </label>
          <span class="sign-text">{{
            status > 30 ? consignee.contactName : ""
          }}</span>
        </el-col>
        <el-col :span="8">
          <label>签收时间: </label>
          <span class="sign-text">{{
            form.status > 30 ? "" : sign.signAtAmend
          }}</span>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import SimpleList from "@components/orderDetail/SimpleList.vue";
import GoodsTotal from "@/views/createOrder/createOrder/components/GoodsTotal.vue";

import {
  transportPrintArr,
  shipperPrintArr,
  consignPrintArr,
  carrierPrintArr
} from "@components/orderDetail/orderData";

import { transport } from "@/api/index";
export default {
  name: "TransportPreview",
  components: {
    SimpleList,
    GoodsTotal
  },
  data () {
    return {
      form: {},
      sign: {}, //签收信息
      signBy: {}, //签收人信息
      waybillDetails: {},
      status: 0,
      transportPrintArr,
      shipperPrintArr,
      consignPrintArr,
      carrierPrintArr,
      customer: {},
      consignee: {},
      carrier: {},
      orderWaybillCache: {},
      toAddress: {},
      fromAddress: {},
      totalList: [],
      tableColumn: [
        {
          label: "序号",
          type: "index",
          width: "50"
        },
        {
          label: "物品编码",
          prop: "materialCode",
          width: "80"
        },
        {
          label: "物品名称",
          prop: "goodsName",
          width: "100"
        },
        {
          label: "规格",
          prop: "spec",
          width: "50"
        },
        {
          label: "物品数量",
          prop: "quantity",
          width: "80"
        },
        {
          label: "总重量 (公斤)",
          prop: "totalWeight",
        },
        {
          label: "总体积 (方)",
          prop: "totalVolume",
        },
        {
          label: "实签数量",
          prop: "signQuantity",
          width: "80"
        },
        {
          label: "异常数量",
          prop: "exceptionQuantity",
          width: "80"
        },
        {
          label: "异常分类",
          prop: "exceptionText",
          width: "100"
        },
        {
          label: "批次",
          prop: "batchNo",
          width: "80"
        }
      ]
    };
  },
  computed: {
    id () {
      return this.$route.query?.waybillId || this.$route.query?.id
    }
  },
  created () {
    this.status = Number(this.$route.query.status);
    this.getDetail();
  },
  mounted () {
    // this.print()
  },
  methods: {
    exceptionListData (data) {
      let list = JSON.parse(JSON.stringify(data));
      delete list.quantity;
      return list;
    },
    async getDetail () {
      let { data } = await transport.getDetail(this.id);
      this.waybillDetails = data;
      let { customer, carrier, consignee, fromAddress, toAddress } = data;
      this.consignee = Object.assign(consignee, data.toContact, {
        createAt: data.createAt
      });

      this.customer = Object.assign(customer, data.fromContact);
      this.carrier = carrier;
      this.fromAddress = fromAddress;
      this.toAddress = toAddress;
      this.sign = data.sign || {};
      if (data.sign) {
        this.signBy = data.sign.signBy;
      }

      if (data.attachments) {
        this.fileList = data?.attachments.filter((x) => x.type === 1);
        this.photo = data?.attachments.filter((x) => x.type === 2);
      }
      //后台不返 物品信息字段，前端自行填充
      this.waybillDetails.goodsList.forEach((item) => {
        let obj = {
          signQuantity: item.quantity,
          exceptionDesc: null,
          exceptionText: "",
          exceptionQuantity: null,
          totalWeight: (item.quantity * item.weight).toFixed(2),
          totalVolume: (item.quantity * item.volume).toFixed(2)
        };

        Object.assign(item, obj);
        if (this.status === 30) {
          item.goodsSign = obj;
        } else if (this.status === 40) {
          item.goodsReceipt = item.goodsSign;
          Object.assign(item, this.exceptionListData(item.goodsSign));
          item.signQuantity = item.goodsSign.quantity;
          item.exceptionText = this.exceptionText(item.goodsSign);
        } else {
          //实签数量 没有签收数据取物品数量，没有回单数据就取签收数量，有回单数据取回单数量
          if (item.goodsReceipt) {
            item.signQuantity = item.goodsReceipt.quantity;
            item.exceptionText = this.exceptionText(item.goodsReceipt);
            Object.assign(item, this.exceptionListData(item.goodsReceipt));
          } else if (item.goodsSign) {
            item.signQuantity = item.goodsSign.quantity;
            item.exceptionText = this.exceptionText(item.goodsSign);
            Object.assign(item, this.exceptionListData(item.goodsSign));
          } else {
            item.signQuantity = item.quantity;
          }
        }
      });
      this.orderWaybillCache = data.waybillCache;
      this.accountTotal();
    },

    accountTotal () {
      let signQuantity = 0; //物品实签数量
      let exceptionQuantity = 0;
      let signSignedQuantity = 0; //签收实签数量
      this.waybillDetails.goodsList.forEach((item) => {
        signQuantity += Number(item.signQuantity || 0); //实签数量
        signSignedQuantity += Number(item.goodsSign?.quantity || 0); //实签数量
        exceptionQuantity += Number(item.exceptionQuantity); //异常数量
      });
      this.totalList = [
        {
          materialCode: "补差",
          totalVolume: this.orderWaybillCache.volumeAddition,
          totalWeight: this.orderWaybillCache.weightAddition
        },
        {
          materialCode: "合计",
          quantity: this.orderWaybillCache.totalQuantity,
          totalVolume: this.orderWaybillCache.calculateVolume,
          totalWeight: this.orderWaybillCache.calculateWeight,
          signQuantity: signQuantity,
          exceptionQuantity: exceptionQuantity,
          signSignedQuantity: signSignedQuantity //实签数量
        }
      ];
    },
    print () {
      setTimeout(() => {
        if (window.document.execCommand("print")) window.close();
        // window.print()
      }, 1000);
    },
    exceptionText (data) {
      let { damageQuantity, lackQuantity, loseQuantity, otherQuantity } = data;
      let exceptionText = `${damageQuantity ? `${damageQuantity} 破损，` : ""}${lackQuantity ? `${lackQuantity} 缺少，` : ""
        }
          ${loseQuantity ? `${loseQuantity} 丢失，` : ""}${otherQuantity ? `${otherQuantity} 其他，` : ""
        }`;
      return exceptionText;
    }
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  height: 100%;
  overflow: auto;
}
.box {
  width: 1000px;
  background: var(--prev-bg-white);
  margin: 0 auto;
  padding: 50px 100px;
}
// @media print {
.sign-text {
  border-bottom: 1px solid #000;
  display: inline-block;
  width: 70%;
}
.precautions {
  line-height: 20px;
  margin-bottom: 10px;
}
/deep/ .el-table th.el-table__cell {
  // border-left: 1px solid var(--prev-border-color-grey);
  background: var(--prev-bg-white);
  .cell {
    height: 40px;
    border-left: none;
  }
}
.sign {
  // height: 50px;
}
.w80p {
  width: 80%;
}
// }
@media screen {
  // .box {
  //   display: none;
  // }
}
.wrap_value {
  white-space: pre-wrap;
  word-break: break-all;
}
.printPic {
  height: 30px;
}
</style>
